/*
 SimpleTreeNode.m
 Copyright (c) 2001-2006, Apple Computer, Inc., all rights reserved.
 Author: Chuck Pisula
 
 Milestones:
 Initially created 3/1/01
 
 Tree node data structure carrying simple data (SimpleTreeNode, and SimpleNodeData).
 */

/*
 IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
 consideration of your agreement to the following terms, and your use, installation, 
 modification or redistribution of this Apple software constitutes acceptance of these 
 terms.  If you do not agree with these terms, please do not use, install, modify or 
 redistribute this Apple software.
 
 In consideration of your agreement to abide by the following terms, and subject to these 
 terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in 
 this original Apple software (the "Apple Software"), to use, reproduce, modify and 
 redistribute the Apple Software, with or without modifications, in source and/or binary 
 forms; provided that if you redistribute the Apple Software in its entirety and without 
 modifications, you must retain this notice and the following text and disclaimers in all 
 such redistributions of the Apple Software.  Neither the name, trademarks, service marks 
 or logos of Apple Computer, Inc. may be used to endorse or promote products derived from 
 the Apple Software without specific prior written permission from Apple. Except as expressly
 stated in this notice, no other rights or licenses, express or implied, are granted by Apple
 herein, including but not limited to any patent rights that may be infringed by your 
 derivative works or by other works in which the Apple Software may be incorporated.
 
 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO WARRANTIES, 
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, 
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS 
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL 
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 
 OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, 
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND 
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR 
 OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#import "SimpleTreeNode.h"
#import "Const.h"

#define KEY_GROUPNAME	@"Group"
#define KEY_ENTRIES	@"Entries"

@implementation SimpleNodeData

- (id)initWithName:(NSString *)str AndPath:(NSString*)thePath AndDictType:(int)theDictType isLeaf:(BOOL)leaf {
    if (self = [super init]) {
        name = [str retain];
        path = [thePath retain];
        dictType = theDictType;
        isLeaf = leaf;
        iconRep = nil;
        isExpandable = !isLeaf;// !isLeaf;
		//        isSelectable = isLeaf;// YES;  
		isSelectable = YES;
    }
    return self;
}

+ (id)leafDataWithName:(NSString*)str AndPath:(NSString*)thePath AndDictType:(int)theDictType{
    // Convenience method to return a leaf node with its name set.
    return [[[SimpleNodeData alloc] initWithName:str AndPath:thePath AndDictType:theDictType isLeaf:YES] autorelease];
}

+ (id)groupDataWithName:(NSString*)str AndPath:(NSString*)thePath AndDictType:(int)theDictType{
    // Convenience method to return a branch node with its name set.
    return [[[SimpleNodeData alloc] initWithName:str AndPath:thePath AndDictType:theDictType isLeaf:NO] autorelease];
}

- (void)dealloc {
	[path release];
    [name release];
    [iconRep release];
    [super dealloc];
}

- (void)setName:(NSString *)str { 
    if (!name || ![name isEqualToString:str]) {
		[name release]; 
		name = [str retain]; 
    }
}

- (NSString *)name { 
    return name; 
}

- (void)setPath:(NSString *)str
{
	if (!path || ![path isEqualToString:str]) 
	{
		[path release]; 
		path = [str retain]; 
    }
}
- (NSString *)path
{
    return path; 
}

- (void)setDictType:(int)tmp_type
{
	dictType = tmp_type; 
}
- (int)dictType
{
    return dictType; 
}

- (void)setIsLeaf:(BOOL)leaf { 
    isLeaf = leaf; 
}

- (BOOL)isLeaf { 
    return isLeaf; 
}

- (BOOL)isGroup { 
    return !isLeaf; 
}

- (void)setIconRep:(NSImage *)ir {
    if (!iconRep || ![iconRep isEqual:ir]) {
		[iconRep release];
		iconRep = [ir retain];
    }
}
- (NSImage *)iconRep {
    return iconRep;
}

- (void)setExpandable:(BOOL)value {
    isExpandable = value;
}

- (BOOL)isExpandable {
    return isExpandable;
}

- (BOOL)isSelectable {
    return isSelectable;
}

- (void)setSelectable:(BOOL)value {
    isSelectable = value;
}

- (NSString *)description { 
    return name; 
}

- (NSComparisonResult)compare:(id)other {
    // We want the data to be sorted by name, so we compare [self name] to [other name]
    if ([other isKindOfClass:[SimpleNodeData class]]) {
        SimpleNodeData *_other = (SimpleNodeData *)other;
        return [name compare:[_other name]];
    } else {
        return NSOrderedAscending;
    }
}

@end

@implementation SimpleTreeNode
// john added
+ (id)initFromDictionary{
	NSString *amtDir = [[NSHomeDirectory()
						 stringByAppendingPathComponent:@"Music"]
						stringByAppendingPathComponent:@"AMT"];

	NSString *library = NSLocalizedString(@"Library", nil);
	
	SimpleNodeData *dataOfOVRoot = [SimpleNodeData groupDataWithName:@"OVRoot" AndPath:@"OVRoot" AndDictType:fileType_other];	//guojihua
    SimpleTreeNode *treeNodeOfOVRoot = [[SimpleTreeNode alloc] initWithData:dataOfOVRoot parent:nil children:[NSArray array]];
	
	//libray	
	SimpleNodeData *dataOfLibray = [SimpleNodeData groupDataWithName:library AndPath:library AndDictType:fileType_other];
	[dataOfLibray setSelectable:NO];
	SimpleTreeNode *treeNodeOfLibray = [[[SimpleTreeNode alloc] initWithData:dataOfLibray parent:nil children:[NSArray array]] autorelease];
	[[treeNodeOfLibray nodeData] setIconRep:[NSImage imageNamed:@"Libray.jpg"]];
	
	[SimpleTreeNode addMusicMoviePictureToNode:treeNodeOfLibray AndRootPath:amtDir];
	
	[treeNodeOfOVRoot insertChild: treeNodeOfLibray atIndex: [treeNodeOfOVRoot numberOfChildren]];
	
	//////////////////////////// start Test
	NSString *deviceDir = [[NSHomeDirectory()
						 stringByAppendingPathComponent:@"Music"]
						stringByAppendingPathComponent:@"Device"];	
	[SimpleTreeNode addDeviceToRootNode:treeNodeOfOVRoot AndDeviceDirPath:deviceDir];
	///////////////////////////	end
	return treeNodeOfOVRoot;
}
+ (SimpleTreeNode *) addMusicMoviePictureToNode:(SimpleTreeNode *)toNode AndRootPath:(NSString *)rootDir
{
	NSString *musicDir = [rootDir stringByAppendingPathComponent:@"Music"];
	NSString *movieDir = [rootDir stringByAppendingPathComponent:@"Movie"];
	NSString *pictureDir = [rootDir stringByAppendingPathComponent:@"Picture"];
	
	NSString *music = NSLocalizedString(@"Music", nil);
	NSString *movie = NSLocalizedString(@"Movie", nil);
	NSString *picture = NSLocalizedString(@"Picture", nil);
	
	SimpleTreeNode *treeNodeOfMusic = [[[SimpleTreeNode alloc] initWithData:[SimpleNodeData groupDataWithName:music AndPath:musicDir AndDictType:fileType_music] parent:nil children:[NSArray array]] autorelease];		
	[[treeNodeOfMusic nodeData] setIconRep:[NSImage imageNamed:@"Music.tiff"]];
	[SimpleTreeNode addChildNodeWithParentNode:treeNodeOfMusic AndPath:musicDir AndDictType:fileType_music];
	
	SimpleTreeNode *treeNodeOfMovie = [[[SimpleTreeNode alloc] initWithData:[SimpleNodeData groupDataWithName:movie AndPath:movieDir AndDictType:fileType_movie] parent:nil children:[NSArray array]] autorelease];		
	[[treeNodeOfMovie nodeData] setIconRep:[NSImage imageNamed:@"Movies.tiff"]];
	[SimpleTreeNode addChildNodeWithParentNode:treeNodeOfMovie AndPath:movieDir AndDictType:fileType_movie];
	
	SimpleTreeNode *treeNodeOfPicture = [[[SimpleTreeNode alloc] initWithData:[SimpleNodeData groupDataWithName:picture AndPath:pictureDir AndDictType:fileType_picture] parent:nil children:[NSArray array]] autorelease];		
	[[treeNodeOfPicture nodeData] setIconRep:[NSImage imageNamed:@"Picture.jpg"]];
	[SimpleTreeNode addChildNodeWithParentNode:treeNodeOfPicture AndPath:pictureDir AndDictType:fileType_picture];
	
	
	[toNode insertChild: treeNodeOfMusic atIndex: [toNode numberOfChildren]];
	[toNode insertChild: treeNodeOfMovie atIndex: [toNode numberOfChildren]];
	[toNode insertChild: treeNodeOfPicture atIndex: [toNode numberOfChildren]];	
	
	return toNode;
}
//Device
+ (SimpleTreeNode *) addDeviceToRootNode:(SimpleTreeNode *)rootNode AndDeviceDirPath:(NSString *)deviceDir
{
	NSString *device = NSLocalizedString(@"Device", nil);
	if([rootNode numberOfChildren] >2)
	{
		device = [device stringByAppendingFormat:@" %d",[rootNode numberOfChildren]];
	}

	
	SimpleNodeData *dataOfDevice = [SimpleNodeData groupDataWithName:device AndPath:device AndDictType:fileType_other];
	[dataOfDevice setSelectable:NO];
	SimpleTreeNode *treeNodeOfDevice = [[[SimpleTreeNode alloc] initWithData:dataOfDevice parent:nil children:[NSArray array]] autorelease];
	[[treeNodeOfDevice nodeData] setIconRep:[NSImage imageNamed:@"Device.jpg"]];
	
	[SimpleTreeNode addMusicMoviePictureToNode:treeNodeOfDevice AndRootPath:deviceDir];
	
	[rootNode insertChild: treeNodeOfDevice atIndex: [rootNode numberOfChildren]];
	return rootNode;
}

+ (SimpleTreeNode *) addChildNodeWithParentNode:(SimpleTreeNode *)parentNode AndPath:(NSString *)path AndDictType:(int)theDictType
{
	NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
	for (NSString *filename in fileList)
	{
		NSString *realFilePath = [path stringByAppendingPathComponent:filename];
		NSString* type = [[[NSFileManager defaultManager] fileAttributesAtPath:realFilePath traverseLink:NO] objectForKey:NSFileType];
		if (type == NSFileTypeDirectory) {
//			NSLog(filename);
			SimpleTreeNode *treeNodeOfListTemp = [[SimpleTreeNode alloc] initWithData:[SimpleNodeData groupDataWithName:filename AndPath:realFilePath AndDictType:theDictType] parent:nil children:[NSArray array]];		
			[[treeNodeOfListTemp nodeData] setIconRep:[NSImage imageNamed:@"Folder.tiff"]];
			[parentNode insertChild: treeNodeOfListTemp atIndex: [parentNode numberOfChildren]];
			[SimpleTreeNode addChildNodeWithParentNode:treeNodeOfListTemp AndPath:realFilePath AndDictType:theDictType];
		}
	}	
	return parentNode;
}
+ (void) updateNode:(SimpleTreeNode *)parentNode
{
	//检测当前的SourceList中的目录是否存在，若不存在，则删除该节点，若该节点正在被选中（Tableview），则转到类型的根路径
	NSString *pathOfParentNod = [[parentNode nodeData]path];
	int theDictType = [[parentNode nodeData]dictType];
	
	NSArray *fileListTMP = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathOfParentNod error:NULL];
	NSMutableArray *fileList = [[NSMutableArray alloc]initWithArray:fileListTMP];
	NSArray *nodes = [parentNode children];
	for(SimpleTreeNode *node in nodes)
	{
		NSString *path = [[node nodeData] path];
		NSString *name = [[node nodeData] name];
		if(![[NSFileManager defaultManager] fileExistsAtPath:path])
		{
			[node removeFromParent];
		} else {
			//			[existFiles addObject:[[node nodeData] name]];
			[fileList removeObject:name];
		}
	}
	//递归调用自己对所有子目录做更新
	for (NSString *filename in fileList)
	{
		NSString *realFilePath = [pathOfParentNod stringByAppendingPathComponent:filename];
		NSString* type = [[[NSFileManager defaultManager] fileAttributesAtPath:realFilePath traverseLink:NO] objectForKey:NSFileType];
		if (type == NSFileTypeDirectory) {
//			NSLog(filename);
			SimpleTreeNode *treeNodeOfListTemp = [[SimpleTreeNode alloc] initWithData:[SimpleNodeData groupDataWithName:filename AndPath:realFilePath AndDictType:theDictType] parent:nil children:[NSArray array]];		
			[[treeNodeOfListTemp nodeData] setIconRep:[NSImage imageNamed:@"Folder.tiff"]];
			[parentNode insertChild: treeNodeOfListTemp atIndex: [parentNode numberOfChildren]];
			[SimpleTreeNode addChildNodeWithParentNode:treeNodeOfListTemp AndPath:realFilePath AndDictType:theDictType];
		}
		
	}
}
+ (void) updateSourceList:(SimpleTreeNode *)rootNode 
{
	//	NSLog(@"Hello From Thread!!!");
	NSArray *levelOneNodes = [rootNode children];
	for(SimpleTreeNode *libDevNode in levelOneNodes)
	{
		NSArray *mmpNode = [libDevNode children];
		for(SimpleTreeNode *typeNode in mmpNode)
		{
			
			NSString *path = [[typeNode nodeData] path];
			if(![[NSFileManager defaultManager] fileExistsAtPath:path])
			{
				[[NSFileManager defaultManager] createDirectoryAtPath:path attributes:nil];
			}
		}
		
		if(![[[libDevNode nodeData] name] isEqualToString:@"Libray"])
		{
			NSArray *mmpNode = [libDevNode children];
			///???????
			[SimpleTreeNode updateNode:[mmpNode objectAtIndex:0]];
			[SimpleTreeNode updateNode:[mmpNode objectAtIndex:1]];
			[SimpleTreeNode updateNode:[mmpNode objectAtIndex:2]];
		} 
	}
}


+ (id)treeFromDictionary{
    return [SimpleTreeNode initFromDictionary];
}

@end

